package com.woniuxy.microutilsserver.listener;

import com.rabbitmq.client.Channel;
import com.woniuxy.microutilsserver.util.MsgUtil;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author unreleased
 * @date 2021/1/29 15:19
 */
@Component
public class RabbitMqListener {
    @RabbitHandler
    @RabbitListener(queues = {"messageQueue"}, containerFactory = "rabbitListenerContainerFactory")
    public void messageListener(Map<String, Object> data, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) {
        //是否成为死信
        boolean ack = true;
        String deliveryId = (String) data.get("deliveryId");
        String tel = (String) data.get("tel");
        try {
            MsgUtil.sendMsg(tel, deliveryId);
        } catch (Exception e) {
            ack = false;
            e.printStackTrace();
        }
        try {
            if (ack) {
                channel.basicAck(deliveryTag, false);
            } else {
                channel.basicNack(deliveryTag, false, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
